const backgroundAudioManager = wx.getBackgroundAudioManager()
const app = getApp();
var api = require('../../api.js');

Page({
  data: {
    settlementOn: false,
    courseInfo: true,
    form: {
      number: 1
    },
    newmoney: 0,
    course_newmoney: 0,
    use_integral: 0,
    judge: false,
    judgeT: false,
    chagneT: false,
    change: false,
    id: 0,//url中的信息
    lesson: 0,//课程的数量
    audioOn: false,//判断是否正在播放
    sliderValue: 0,//slider的值

    audioId: "",//判断是第几个--循环播放
    audioCoverImgUrl: "",
    audioSrc: "",
    audioTitle: "",
    audioSinger: "",
    audioAllTime: "",

    isFirst: true, //第一次
    // isFirst:false, //第一次

    list: [],
  },
  onLoad: function (options) {
    console.log("onLoad");
    console.log(options);
    wx.setStorageSync("id", options.lessonId);
    console.log("_____________________测试backgroundAudioManager______________________");
    console.log(backgroundAudioManager);
  },
  onReady: function () {
    console.log("onReady");
    // this.audio();

  },
  onShow: function () {
    console.log("onShow");
    var equipmentSystem = wx.getStorageSync('equipmentSystem');
    app.bind();
    var id = wx.getStorageSync("id");
    this.setData({
      id:id,
      equipmentSystem: equipmentSystem
    })
    console.log(this.data.id);
    this.getAudioDetail();

  },
  onHide: function () {
    console.log("onHide");
    var url = app.getcurrentPageLessonId();
    wx.setStorageSync("from_url", url);
  },
  onUnload: function () {
    console.log("onUnload");
    this.pause();
  },
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {

    app.bind();
    var pages = getCurrentPages(); //获取加载的页面
    var currentPage = pages[pages.length - 1]; //获取当前页面的对象
    var options = currentPage.options; //如果要获取url中所带的参数可以查看options
    this.setData({
      id: options.id
    })
    this.getAudioDetail();

    // 显示顶部刷新图标  
    wx.showNavigationBarLoading();

    // 隐藏导航栏加载框  
    wx.hideNavigationBarLoading();

    //停止下拉刷新
    wx.stopPullDownRefresh();

  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {
    var url = app.getcurrentPageLessonId();

    var user_id = wx.getStorageSync('user_id');
    return {
      path: url + "&user_id=" + user_id,
      title: '得道1314'
    };
  },
  // 获取基本信息
  getAudioDetail: function () {
    var that = this;
    var access_token = wx.getStorageSync('access_token');
    var url = api.three.audioDetail;
    var id = that.data.id;
    wx.request({
      url: api.three.audioDetail,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: that.data.id
      },
      success: function (e) {

        console.log(e);
        var list = e.data.data.list;
        console.log(list);

        if (e.data.code == 0) {

          that.setData({
            list: list,
            audioCoverImgUrl: list[0].cover_pic,
            lesson: e.data.data.row_count
          })

          that.getOnlineDetail();
          that.getOfflineDetail();

          if (list[0].lesson_buy == true) {
            that.setData({
              judge: true,
              change: true,
              show: false
            })
          }

          if (list[0].course_buy == true) {
            that.setData({
              judgeT: true,
              changeT: true,
              show_attr_picker: false
            })
          }

        } else {
          wx.navigateTo({
            url: '/pages/grant/grant'
          })
        }

      }
    });
  },

  // 顺序播放
  getAudioInfo: function (index) {

    var that = this;

    console.log("——————————————————————开始测试——————————————————————");
    console.log(that.data.list[index]);

    var current = that.data.list[index];
    var allTime = current.audio_length;
    if (allTime == 0) {
      allTime = 1000
    } else {
      var minute = Number(allTime.split(":")[0]);
      var second = Number(allTime.split(":")[1]);
      allTime = minute * 60 + second;      
    }

    console.log(allTime);

    that.setData({
      audioId: index,
      audioCoverImgUrl: current.cover_pic,
      audioTitle: current.title,
      audioSinger: current.title,
      audioAllTime: allTime,
    })

    console.log(that.data.audioId);
    console.log(that.data.audioCoverImgUrl);
    console.log(that.data.audioTitle);
    console.log(that.data.audioSinger);
    console.log(that.data.audioAllTime);


    var isBuy = current.lesson_buy;
    console.log(isBuy);

    if (isBuy == true) {

      that.setData({
        audioSrc: current.audio_url,
      })
      that.audio();
      that.changeOn();

    } else {

      wx.showToast({
        title: '请先购买',
        icon: 'none',
      })

    }

  },

  // 音频播放主件
  audio: function () {
    console.log("___________________audio开始_______________________");
    console.log(backgroundAudioManager);
    let that = this;
    console.log(that.data);
    backgroundAudioManager.autoplay = true
    backgroundAudioManager.title = that.data.audioTitle
    backgroundAudioManager.epname = that.data.audioSinger
    backgroundAudioManager.singer = that.data.audioSinger
    backgroundAudioManager.coverImgUrl = that.data.audioCoverImgUrl
    backgroundAudioManager.src = that.data.audioSrc
    // backgroundAudioManager.title = "张 - 李"
    // backgroundAudioManager.epname = "张学友1 - 李香兰"
    // backgroundAudioManager.singer = "张学友2 - 李香兰"
    // backgroundAudioManager.coverImgUrl = "https://videocgmm.fxm365.com/snapshot/3052f065cc114f43b3f7005bd19ecd5a00001.jpg?auth_key=1528790554-6a61f6852bf042bb8a9b650f42d8999e-0-ba848d4a96d2768cfd6954223a31f6d4"
    // backgroundAudioManager.src = "https://videocgmm.fxm365.com/3052f065cc114f43b3f7005bd19ecd5a/e334dfaed0d14f72af70a44a00dd6736-5287d2089db37e62345123a1be272f8b.mp4?auth_key=1528790554-08df5bb5637d42c3834b271e5ba4f676-0-6f882686fc4951bf2e590644dbae2513"
    // backgroundAudioManager.src = "http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46"
    // backgroundAudioManager.src = "https://audio.zhouzi.fxm365.com/%E7%BA%AF%E9%9F%B3%E9%A2%91/test.mp3"
    backgroundAudioManager.onPlay(() => {
      console.log("1、音频开始播放");
      console.log(backgroundAudioManager);
      that.setData({
        audioOn: true,
      })
    })
    backgroundAudioManager.onWaiting(() => {
      console.log("2、音频加载中");
      console.log(backgroundAudioManager);
    })
    backgroundAudioManager.onCanplay(() => {
      console.log("3、音频进入可以播放状态");
    })
    backgroundAudioManager.onTimeUpdate(() => {
      console.log("4、音频播放进度更新");
      var value = (backgroundAudioManager.currentTime / backgroundAudioManager.duration) * 100;
      that.setData({
        sliderValue: value
      })
    })
    backgroundAudioManager.onEnded((e) => {
      console.log("5、音频自然播放结束");
      // 按列表顺序自动播放
      var id = that.data.audioId;
      var length = that.data.list.length;
      console.log(id);
      console.log(length);
      if (id < length - 1) {
        id++;
        var list = that.data.list[id];
        console.log(list);
        that.getAudioInfo(id);
      } else {
        that.setData({
          audioOn: false,
          sliderValue: 0,
        })
      }
    })
    backgroundAudioManager.onPause(() => {
      console.log("6、音频暂停播放");
      that.setData({
        audioOn: false,
      })
    })
    backgroundAudioManager.onStop(() => {
      console.log("7、音频停止播放");
      that.setData({
        audioOn: false,
      })
    })
    backgroundAudioManager.onError((e) => {
      console.log("0、音频播放错误");
      console.log(e);
      that.setData({
        audioOn: false,
      })
    })

    backgroundAudioManager.onPrev(() => {
      console.log("prev、用户在系统音乐播放面板点击上一曲事件");
    })
    backgroundAudioManager.onNext(() => {
      console.log("next、用户在系统音乐播放面板点击下一曲事件");
    })
  },
  play: function (e) {
    var that = this;
    backgroundAudioManager.play();
    backgroundAudioManager.autoplay = true
    backgroundAudioManager.title = that.data.audioTitle
    backgroundAudioManager.epname = that.data.audioSinger
    backgroundAudioManager.singer = that.data.audioSinger
    backgroundAudioManager.coverImgUrl = that.data.audioCoverImgUrl
    backgroundAudioManager.src = that.data.audioSrc
  },
  pause: function () {
    backgroundAudioManager.pause();
  },
  // 第一次播放
  playFirst: function (e) {
    var that = this;
    console.log(that.data);
    var current = that.data.list[0];
    var allTime = current.audio_length;
    var minute = Number(allTime.split(":")[0]);
    var second = Number(allTime.split(":")[1]);
    allTime = minute * 60 + second;

    that.setData({
      audioId: 0,
      audioCoverImgUrl: current.cover_pic,
      audioSrc: current.audio_url,
      audioTitle: current.title,
      audioSinger: current.title,
      audioAllTime: allTime,
      isFirst: false,
      audioOn: true,
    })
    that.getAudioInfo(0);
    that.getOnlineDetail();
    that.getOfflineDetail();
  },
  // 开始播放
  restart: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;

    that.setData({
      listDetail: that.data.list[index]
    })
    // console.log(that.data.listDetail);

    if (that.data.listDetail.lesson_buy == true) {
      that.setData({
        judge: true,
        change: true,
        show: false
      })
    }

    if (that.data.listDetail.course_buy == true) {
      that.setData({
        judgeT: true,
        changeT: true,
        show_attr_picker: false
      })
    }

    that.getAudioInfo(index);
    that.getOnlineDetail();
    that.getOfflineDetail();
  },
  // 顺序播放的一部分
  changeOn: function () {
    // 改变列表中的on
    var that = this;
    console.log(that.data.list);
    var id = that.data.audioId;
    var allList = that.data.list;
    for (var j = 0; j < allList.length; j++) {
      allList[j].on = false;
    }
    allList[id].on = true;
    that.setData({
      list: allList
    })
  },
  sliderchange: function (e) {
    var that = this;
    var allTime = that.data.audioAllTime;
    var time = e.detail.value;
    var stime = time / 100 * allTime;
    that.setData({
      audioNowTime: stime
    })
    backgroundAudioManager.play();
    backgroundAudioManager.seek(stime);
  },


  //线上、线下切换
  tab: function (e) {

    var tab = e.currentTarget.dataset.tab;
    console.log(this.data.listDetail.lesson_buy)
    if (tab == "online") {

      if (this.data.listDetail.lesson_buy == true) {
        this.setData({
          judge: true,
          change: true,
          show: false
        })
        console.log(this.data.judge)
        console.log(this.data.change)
        console.log(this.data.show)
      } else {
        this.setData({
          tab_online: "active",
          tab_offline: "",
          show: true,
          change: false,
          show_attr_picker: false,
        })
      }
      this.getTotalMoney();
      console.log(this.data.change)

    } else {
      if (this.data.listDetail.course_buy == true) {
        this.setData({
          judgeT: true,
          changeT: true,
          show_attr_picker: false
        })
      } else {
        this.setData({
          tab_online: "",
          tab_offline: "active",
          show_attr_picker: true,
          changeT: false,
        })
      }
      this.getTotalMoneyOff();
      if (this.data.courseInfo == false) {
        wx.showToast({
          title: '该课程还未有线下课',
          icon: 'none',
        })
      }
    }
  },

  //线上课提交前预览页面
  getOnlineDetail: function () {
    console.log("111111111111111111111111111111111111111111111111111111111111111")

    var page = this;
    console.log(page.data.listDetail)
    var access_token = wx.getStorageSync('access_token');
    wx.request({
      url: api.lessonOrder.submitPreview,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.listDetail.lesson_id,
      },

      success: function (res) {
        console.log(res);

        if (res.data.code == 0) {
          page.setData({
            lessonInfo: res.data.data.lesson_info,
            user: res.data.data.user,
            money: res.data.data.user.integral2money,
            integral: res.data.data.user.integral,
            price: res.data.data.lesson_info.price
          })
          console.log(page.data.price)

        } else {
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }

      }
    });
  },


  //线上开关选择器
  switchChange: function (e) {
    var page = this;
    console.log(e);
    page.setData({
      switchValue: e.detail.value
    })
    console.log(page.data.integral);

    if (page.data.switchValue == true) {
      page.setData({
        newmoney: page.data.money,
        use_integral: page.data.integral,
      })
    } else {
      page.setData({
        newmoney: 0,
        use_integral: 0
      })
    }
    page.getTotalMoney();
  },


  //线上获取总额
  getTotalMoney: function () {
    var page = this;
    var user_newmoney = page.data.newmoney;

    var price = page.data.price;
    console.log(user_newmoney)
    console.log(page.data.newmoney)
    var totalMoney = parseFloat(price) - parseFloat(user_newmoney)
    page.setData({
      totalMoney: totalMoney
    })
  },

  //线上结算
  settlementBtn: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    page.getTotalMoney();
    console.log(page.data.use_integral)

    page.setData({
      settlementOn: true
    })


    wx.request({
      url: api.lessonOrder.submit,
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.listDetail.lesson_id,
        num: 1,
        use_integral: page.data.use_integral,
      },

      success: function (res) {
        console.log(res);
        var data = res.data.data
        if (res.data.code == 0) {
          page.getAudioDetail();
          if (res.data.msg == "订单支付成功") {
            page.setData({
              judge: true,
              change: true,
            })
            console.log(4554654665465)
          } else {
            //发起支付
            wx.requestPayment({
              timeStamp: data.timeStamp,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: function (res) {
                console.log(res)
                page.setData({
                  judge: true,
                  change: true,
                })
                console.log(11111111111)
              },
              fail: function (res) {

              },
              complete: function (res) {

              }
            })
          }

        } else if (res.data.code == -1) {
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }

      }
    });
  },






  //线下提交前预览页面
  getOfflineDetail: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    wx.request({
      url: api.courseOrder.submitPreview,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.listDetail.course_id,
      },

      success: function (res) {
        console.log(res);

        if (res.data.code == 0) {

          if (res.data.data.course_info == null) {
            page.setData({
              changeT: true,
              judgeT: false,
              courseInfo: false
            })

          } else {
            page.setData({
              course_info: res.data.data.course_info,
              course_user: res.data.data.user,
              course_money: res.data.data.user.integral2money,
              course_integral: res.data.data.user.integral,
              course_price: res.data.data.course_info.price
            })
            console.log(page.data.course_money)
          }



        } else {
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }

      }
    });
  },

  //数量相加
  numberSub: function () {
    var page = this;
    var num = page.data.form.number;
    if (num <= 1)
      return true;
    num--;
    page.setData({
      form: {
        number: num,
      }
    });
    page.getTotalMoneyOff();
  },
  //数量减少
  numberAdd: function () {
    var page = this;
    var num = page.data.form.number;
    num++;
    page.setData({
      form: {
        number: num,
      }
    });
    page.getTotalMoneyOff();
  },
  //改变输入框内的数量
  numberBlur: function (e) {
    var page = this;
    var num = e.detail.value;
    num = parseInt(num);
    if (isNaN(num))
      num = 1;
    if (num <= 0)
      num = 1;
    page.setData({
      form: {
        number: num,
      }
    });
    page.getTotalMoneyOff();
  },

  //线下开关选择器
  switchOff: function (e) {
    var page = this;
    console.log(e);
    page.setData({
      switchValue: e.detail.value
    })
    if (page.data.switchValue == true) {
      page.setData({
        course_newmoney: page.data.course_money,
        course_integral: page.data.course_integral,
      })
    } else {
      page.setData({
        course_newmoney: 0,
        course_integral: 0
      })
    }
    console.log(page.data.switchValue);
    console.log(page.data.course_integral);
    console.log(page.data.course_money);
    console.log(page.data.course_newmoney);
    page.getTotalMoneyOff();
  },


  //线下获取总额
  getTotalMoneyOff: function () {
    var page = this;
    var course_newmoney = page.data.course_newmoney;

    var course_price = page.data.course_price;
    var formNumber = page.data.form.number;
    var totalPrice = parseFloat(course_price) * parseFloat(formNumber)
    console.log(course_newmoney)
    console.log(course_price);
    console.log(totalPrice);
    var course_totalMoney = parseFloat(totalPrice) - parseFloat(course_newmoney);
    console.log(course_totalMoney)
    page.setData({
      course_totalMoney: course_totalMoney
    })
  },

  //线下结算
  settlementOffBtn: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    console.log(page.data.course_id)
    wx.request({
      url: api.courseOrder.submit,
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.listDetail.course_id,
        num: page.data.form.number,
        use_integral: page.data.course_integral,
      },

      success: function (res) {
        console.log(res);
        var data = res.data.data
        if (res.data.code == 0) {
          page.getAudioDetail();
          if (res.data.msg == "订单支付成功") {
            page.setData({
              judgeT: true,
              changeT: true,
            })
            console.log(4554654665465)
          } else {
            //发起支付
            wx.requestPayment({
              timeStamp: data.timeStamp,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: function (res) {


                console.log(res)
                page.setData({
                  judgeT: true,
                  changeT: true,
                })


              },
              fail: function (res) {

              },
              complete: function (res) {

              }
            })
          }


        } else if (res.data.code == -1) {
          wx.reLaunch({
            url: '/pages/grant/grant',
          })
        }

      }
    });
  },

  //点击弹窗退出
  clear: function () {
    var page = this;
    page.setData({
      show_attr: false,
      show_attr_picker: false,
      changeT: true,
      show: false,
      change: true,
    })
  },







})